<template>
  <div>
    <a-modal
      :title="title"
      :visible="visible"
      class="large-modal"
      @ok="handleOk"
      @cancel="$emit('update:visible',false)"
    >
      <a-row v-loading="loading">
        <a-col :span="6">
          <a-tree
            style="height: 400px; overflow: auto"
            :selected-keys.sync="selectedKeys"
            :replace-fields="replaceFields"
            :tree-data="orgTreeData"
            @select="getOrgPerson"
          />
        </a-col>
        <a-col :span="1" />
        <a-col :span="17">
          <a-row>
            <a-col
              :span="24"
              class="mb20p flex align-items-center"
            >
              <a-input
                v-model.trim="content"
                placeholder="员工名称/电话号码/员工编号"
              />
              <a-button
                type="primary"
                class="ml20p"
                @click="onSearch"
              >搜索</a-button>
              <a-button
                class="ml20p"
                @click="content = '';onSearch()"
              >重置</a-button>
            </a-col>
          </a-row>
          <a-row>
            <a-tag
              v-for="(item,index) of selectPersons"
              :key="item.id"
              class="mb20p"
              :closable="selectPersons.length>1?true:false"
              @close="removePerson($event,index)"
            >
              {{ item.name }}
            </a-tag>
          </a-row>
          <div v-if="showAdd">
            <a-button
              v-show="isAdd"
              type="primary"
              style="margin-bottom: 10px"
              @click="isAdd = false"
            >
              添加外部人员
            </a-button>
            <div
              v-show="!isAdd"
              class="flex align-items-center mb20p"
            >
              参与人名称：
              <BaseInput
                v-model="outside"
                style="width: 30%"
                placeholder="请输入外部参与人员"
              />
              <a-button
                type="primary"
                style="margin-left: 20px"
                @click="getOutside"
              >添加</a-button>
              <a-button
                style="margin-left: 20px"
                @click="isAdd = true"
              >取消</a-button>
            </div>
          </div>
          <b-table
            ref="table"
            :columns="columns"
            :select-config="{use : mode !== 'multiple', type: 'radio', rowKey: 'userId'}"
            :scroll="{ y: 260 }"
            :request="loadData"
            :page-keys="['pageNumber', 'pageSize','total']"
            :out-selected-row-keys="selectedRowKeys"
            @row-click="(e,record) => option(record)"
          >
            <template
              v-if="mode === 'multiple'"
              slot="action"
              slot-scope="text, record"
            >
              <a @click="option(record)">{{ optionText(record) }}</a>
            </template>
          </b-table>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { getCustOrgTree, getStaff } from '@/api/subassembly/TreeSelectOrganization'
import { getOneOrgUsers } from '@/api/commons'

export default {
  props: {
    list: {
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: () => '添加参与人'
    },
    mode: {
      type: String,
      default: 'multiple'
    },
    showAdd: {
      type: Boolean,
      default: () => false
    },
    orgQuery: {
      type: Object,
      default: () => null
    },
    orgId: {
      type: String,
      default: () => ''
      // default: () => '06bcbdacb4374523bdaf66586c45f749'
    },
    needData: {
      type: Boolean,
      default: () => true
    },
    maxSelectLength: {
      type: Number,
      default: () => null
    },
    //主键
    primaryKey: {
      type: String,
      default: 'id'
    }
  },
  data() {
    return {
      personsRes: null,
      personsArgs: null,
      treeDataRes: null,
      treeDataQuery: null,

      columns: [
        {
          title: '员工名称',
          dataIndex: 'name'
        },
        {
          title: '员工编号',
          dataIndex: 'jobNum'
        },
        {
          title: '电话号码',
          dataIndex: 'phoneNum'
        },
        {
          title: '职称',
          dataIndex: 'jobTitle'
        },
        {
          title: '操作',
          width: '100px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      queryParam: {},
      loadData: async (params) => {
        if (!this.selectedKeys.length) {
          return { code: 200, data: [] }
        }
        let args = Object.assign(params, this.queryParam)
        args.rootOrgId = this.selectedKeys[0]
        // args.orgId = this.selectedKeys[0]
        args.queryPostRelation = true
        // args.orgType = '2'
        // args.and = true
        // args.types=[0]// 公司内部用户
        // console.log('args=',args,'this.personArgs=',this.personsArgs)
        let res = this.personsRes == null || !_.isEqual(this.personsArgs, args) ? await getOneOrgUsers(args) : this.personsRes
        //console.log(res)
        this.personsRes = res
        this.personsArgs = args
        return { ...res, data: res.list }
      },
      isAdd: true,
      content: undefined,
      loading: false,

      selectedKeys: [],
      orgTreeData: [],
      replaceFields: {
        children: 'children',
        title: 'label',
        key: 'id'
      },
      selectPersons: [],
      selectedRowKeys: []
    }
  },
  created() {},
  watch: {
    async visible(val) {
      if (val && this.needData) {
        this.selectPersons = this.$clone(this.list)
        this.selectedRowKeys = this.list.map((v) => v.id)
        // getCustOrgTree(this.orgQuery ? this.orgQuery : { containVirtual: 0 }).then((res) => {
        this.loading = true
        let query = this.orgQuery ? this.orgQuery: {
          baseOrgType: 0, // 是否基础组织 0否 1是
              containVirtual: 0 //是否包含虚拟组织 0包含 1 不包含
            }
        //缓存查询对象
        let res = this.treeDataRes == null ||  !_.isEqual(this.treeDataQuery, query) ? await getCustOrgTree(query) : this.treeDataRes
        this.treeDataRes = res
        this.treeDataQuery = query

        this.loading = false
        if (res.data && res.data.length > 0) {
          this.orgTreeData = res.data
          if (this.orgId) {
            this.recursion(this.orgTreeData, null)
          }
          this.selectedKeys = [this.orgTreeData[0].id]
          this.$refs.table.getData(null, true)
        }
      } else {
        this.selectPersons = []
        this.queryParam = {}
        this.content = ''
      }
    }
  },
  methods: {
    recursion(items, parent) {
      for (let i = 0; i < items.length; i++) {
        let item = items[i]
        if (item.id === this.orgId) {
          this.orgTreeData = [item]
        } else {
          if (item.children) {
            this.recursion(item.children, item)
          }
        }
      }
    },
    removePerson(e, index) {
      e && e.preventDefault()
      this.selectPersons.splice(index, 1)
    },
    optionText(record) {
      let res = this.selectPersons.find((v) => v[this.primaryKey] === record[this.primaryKey])
      return res ? '删除' : '添加'
    },
    option(record) {
      if (this.mode !== 'multiple') {
        this.selectPersons = []
      }
      let resIndex = this.selectPersons.findIndex((v) => v[this.primaryKey] === record[this.primaryKey])
      if (resIndex !== -1) {
        this.removePerson(null, resIndex)
      } else {
        this.selectPersons.push(record)
      }
    },
    handleOk(e) {
      if (this.mode !== 'single' && this.maxSelectLength !== null) {
        if (this.selectPersons.length > this.maxSelectLength) {
          return this.$noticeWarning(`最多可选中${this.maxSelectLength}人`)
        }
      }
      this.selectPersons.map((v) => {
        v.orgId = this.selectedKeys[0]
      })
      console.log('this.selectPersons=',this.selectPersons)
      this.$emit('update:visible', false)
      this.$emit('update:list', this.selectPersons)
      this.$emit('getSelectPerson', this.selectPersons)
    },
    getOrgPerson(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.onSearch()
    },
    getOutside() {},
    onSearch() {
      this.queryParam.key = this.content
      this.$refs.table.getData(null, true)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
